package com.kds.smarthome.config;

import com.kds.smarthome.annotation.DateRange;
import com.kds.smarthome.controller.vo.DateObject;
import com.kds.smarthome.common.DateType;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class DateObjectArgumentResolver implements HandlerMethodArgumentResolver {

    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormat.forPattern("yyyy-MM-dd");

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(DateRange.class) &&
               (parameter.getParameterType().equals(DateObject.class) ||
                parameter.getParameterType().equals(List.class));
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();

        String typeCode = request.getParameter("dateType");
        String values = request.getParameter("dateValue");

        if (typeCode == null || values == null) {
            throw new IllegalArgumentException("Missing required parameters: type and values");
        }

        DateType dateType = DateType.fromCode(typeCode);
        String[] dateValues = values.split(",");

        List<DateObject> dateObjects = new ArrayList<>();
        for (String value : dateValues) {
            try {
                DateTime dateTime = DATE_FORMATTER.parseDateTime(value.trim());
                DateObject dateObject = createDateObject(dateType, dateTime, value.trim());
                dateObjects.add(dateObject);
            } catch (IllegalArgumentException e) {
                throw new IllegalArgumentException("Invalid date format: " + value);
            }
        }

        // 如果参数类型是单个DateObject，返回第一个
        if (parameter.getParameterType().equals(DateObject.class)) {
            return dateObjects.isEmpty() ? null : dateObjects.get(0);
        }

        return dateObjects;
    }

    private DateObject createDateObject(DateType dateType, DateTime dateTime, String value) {
        DateObject dateObject = new DateObject();
        dateObject.setType(dateType);
        dateObject.setValue(value);

        switch (dateType) {
            case DAY:
                dateObject.setStartTime(dateTime.withTimeAtStartOfDay().toDate());
                dateObject.setEndTime(dateTime.plusDays(1).withTimeAtStartOfDay().toDate());
                break;
            case MONTH:
                dateObject.setStartTime(dateTime.withDayOfMonth(1).withTimeAtStartOfDay().toDate());
                dateObject.setEndTime(dateTime.plusMonths(1).withDayOfMonth(1).withTimeAtStartOfDay().toDate());
                break;
            case YEAR:
                dateObject.setStartTime(dateTime.withMonthOfYear(1).withDayOfMonth(1).withTimeAtStartOfDay().toDate());
                dateObject.setEndTime(dateTime.plusYears(1).withMonthOfYear(1).withDayOfMonth(1).withTimeAtStartOfDay().toDate());
                break;
        }

        return dateObject;
    }
}
